using System;
using System.IO;
using Velocity4Net.Ctx;
using Velocity4Net.Util.Introspection;
using Velocity4Net.App.Events;
using Velocity4Net.Runtime.Logging;
namespace Velocity4Net.Runtime.Parse.AST
{
    /**
     * Node for the #set directive
     *
     * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
     * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
     * @version $Id: ASTSetDirective.java 720228 2008-11-24 16:58:33Z nbubna $
     */
    public class ASTSetDirective : SimpleNode
    {
        private String leftReference = "";
        private INode right = null;
        private ASTReference left = null;
        bool logOnNull = false;
        private bool allowNull = false;
        private bool isInitialized;

        /**
         *  This is really immutable after the init, so keep one for this node
         */
        protected Info uberInfo;

        /**
         * Indicates if we are running in strict reference mode.
         */
        protected bool strictRef = false;

        /**
         * @param id
         */
        public ASTSetDirective(int id)
            : base(id)
        {
        }

        /**
         * @param p
         * @param id
         */
        public ASTSetDirective(Parser p, int id)
            : base(p, id)
        {
        }

        /**
         *  simple init.  We can get the RHS and LHS as the the tree structure is static
         * @param context
         * @param data
         * @return Init result.
         * @throws TemplateInitException
         */
        public override Object Init(InternalContextAdapter context, Object data)
        {
            /** This method is synchronized to prevent double initialization or initialization while rendering **/
            lock (this)
            {
                if (!isInitialized)
                {
                    /*
                     *  init the tree correctly
                     */

                    base.Init(context, data);

                    uberInfo = new Info(TemplateName,
                            Line, Column);

                    right = getRightHandSide();
                    left = getLeftHandSide();

                    logOnNull = rsvc.GetBoolean(RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true);
                    allowNull = rsvc.GetBoolean(RuntimeConstants.SET_NULL_ALLOWED, false);
                    strictRef = rsvc.GetBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
                    if (strictRef) allowNull = true;  // strictRef implies allowNull

                    /*
                     *  grab this now.  No need to redo each time
                     */
                    leftReference = left.FirstToken.image.Substring(1);

                    isInitialized = true;
                }

                return data;
            }
        }

        /**
         *   puts the value of the RHS into the context under the key of the LHS
         * @param context
         * @param writer
         * @return True if rendering was sucessful.
         * @throws IOException
         * @throws MethodInvocationException
         */
        public override bool Render(InternalContextAdapter context, TextWriter writer)
        {
            /*
             *  get the RHS node, and its value
             */

            Object value = right.GetValue(context);

            /*
             * it's an error if we don't have a value of some sort AND
             * it is not allowed by configuration
             */

            if (!allowNull)
            {
                if (value == null)
                {
                    /*
                     *  first, are we supposed to say anything anyway?
                     */
                    if (logOnNull)
                    {
                        bool doit = EventHandlerUtil.shouldLogOnNullSet(rsvc, context, left.Literal(), right.Literal());

                        if (doit && rsvc.getLog().isDebugEnabled())
                        {
                            rsvc.getLog().debug("RHS of #set statement is null. Context will not be modified. "
                                          + Log.formatFileString(this));
                        }
                    }

                    String rightReference = null;
                    if (right is ASTExpression)
                    {
                        rightReference = ((ASTExpression)right).LastToken.image;
                    }
                    EventHandlerUtil.invalidSetMethod(rsvc, context, leftReference, rightReference, uberInfo);

                    return false;
                }
            }

            if (value == null && !strictRef)
            {
                String rightReference = null;
                if (right is ASTExpression)
                {
                    rightReference = ((ASTExpression)right).LastToken.image;
                }
                EventHandlerUtil.invalidSetMethod(rsvc, context, leftReference, rightReference, uberInfo);

                /*
                 * if RHS is null, remove simple LHS from context
                 * or call setValue() with a null value for complex LHS
                 */
                if (left.jjtGetNumChildren() == 0)
                {
                    context.Remove(leftReference);
                }
                else
                {
                    left.setValue(context, null);
                }

                return false;

            }
            else
            {
                /*
                 *  if the LHS is simple, just punch the value into the context
                 *  otherwise, use the setValue() method do to it.
                 *  Maybe we should always use setValue()
                 */

                if (left.jjtGetNumChildren() == 0)
                {
                    context.Put(leftReference, value);
                }
                else
                {
                    left.setValue(context, value);
                }
            }

            return true;
        }

        /**
         *  returns the ASTReference that is the LHS of the set statememt
         *  
         *  @return left hand side of #set statement
         */
        private ASTReference getLeftHandSide()
        {
            return (ASTReference)jjtGetChild(0);
        }

        /**
         *  returns the RHS Node of the set statement
         *  
         *  @return right hand side of #set statement
         */
        private INode getRightHandSide()
        {
            return jjtGetChild(1);
        }
    }
}
